#Makefile - src/ 目录下
SHELL := /bin/bash

ROOT_DIR := ..
INS_PATH := $(ROOT_DIR)/install
INC_PATH := $(INS_PATH)/include
LIB_PATH := $(INS_PATH)/lib
BIN_PATH := $(INS_PATH)/bin

LIBNAME := canacc
CC := gcc
AR := ar
ARFLAGS := rcs

#所有源文件
SRCS := $(wildcard *.c)
OBJS := $(SRCS:.c=.o)

CFLAGS := -Wall -Wextra -O2 -I$(INC_PATH) -pthread
LDFLAGS := -lpthread -ldl -lm

.PHONY: all dirs lib main install clean

all: dirs lib main install clean_obj
	@echo "Build completed. Intermediate .o files removed."

dirs:
	@mkdir -p $(INS_PATH)/{bin,include,lib}
	@echo "Created directories in $(INS_PATH)"

#编译所有 .c 文件
%.o: %.c %.h
	$(CC) $(CFLAGS) -c $< -o $@

#生成静态库
lib: $(OBJS)
	$(AR) $(ARFLAGS) $(LIB_PATH)/lib$(LIBNAME).a $(OBJS)
	@echo "Static library lib$(LIBNAME).a built and copied to $(LIB_PATH)"

#编译主程序
main: main.o lib
	$(CC) main.o -o main \
		-L$(LIB_PATH) -l$(LIBNAME) \
		$(LDFLAGS)
	@cp main $(BIN_PATH)/
	@echo "Executable 'main' built and installed to $(BIN_PATH)"

#安装头文件
install: main
	@cp *.h $(INC_PATH)/
	@echo "Headers installed to $(INC_PATH)"

#清理 .o 文件（构建完成后自动执行）
clean_obj:
	@rm -f $(OBJS)
	@echo "Removed intermediate .o files"

#完全清理（可手动调用）
clean:
	@rm -f main
	@rm -f $(LIB_PATH)/lib$(LIBNAME).a
	@rm -f $(BIN_PATH)/main
	@rm -f $(OBJS)   #冗余保险
	@echo "Full clean: removed all build artifacts"
